package com.easylinkin.linkappapi.common.utils.file;

import com.easylinkin.linkappapi.common.utils.StringUtil;
import com.easylinkin.linkappapi.elasticsearch.entity.DateSourceEnergyRecord;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * class info :文件打包工具类
 *
 * @author liuqihang
 * @date 2021/6/18 11:18
 */
@Slf4j
public class ZipFileUtil {

    public static String zipSuffix = ".zip";
    public static String fileNameField = "x-oss-meta-filename";

    /**
     *
     * @param fileName  压缩后的文件名称：测试.zip
     * @param fileExtList    子文件名称 + 文件流
     * @return
     */
    public static File compressionZipFile(String fileName, List<FileExt> fileExtList){
        File zipFile = null;
        try {
            zipFile = File.createTempFile(fileName, zipSuffix);
            FileOutputStream f = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(f);

            //去重
            Map<String, List<FileExt>> collect = fileExtList.stream().collect(Collectors.groupingBy(FileExt::getFileName));
            fileExtList.clear();
            for (Map.Entry<String, List<FileExt>> entry : collect.entrySet()){
                fileExtList.add(entry.getValue().get(0));
            }

            for (FileExt zfe : fileExtList) {
                InputStream inputStream = zfe.getInputStream();
                if(StringUtils.isEmpty(zfe.getFolder())){
                    zfe.setFolder("/");
                }else{
                    zfe.setFolder(zfe.getFolder() + "/");
                }
                zos.putNextEntry(new ZipEntry(zfe.getFolder() + zfe.getFileName()));
                byte[] buf = new byte[1024 * 1024];
                int size = 0;
                while ((size = inputStream.read(buf)) != -1) {
                    zos.write(buf, 0, size);
                }
                inputStream.close();
                zos.closeEntry();
            }
            zos.close();
        } catch (IOException e) {
            log.error("压缩文件是报错：{}",e.getMessage());
            e.printStackTrace();
        }
        return zipFile;
    }

    public static InputStream getFileInputStream(String fileName, List<FileExt> zipFileExtList) throws Exception {
        File file = compressionZipFile(fileName, zipFileExtList);
        return new FileInputStream(file);
    }

    /**
     *根据网络文件路径获取输入流
     * @param url
     * @return
     */
    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            log.error("获取网络图片出现异常，图片路径为：{}.异常信息为：{}", url, e.getMessage());
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }

    public static FileExt getFileInfoByUrl(String url){
        FileExt zipFileExt = new FileExt();
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            //30s
            connection.setReadTimeout(30000);
            connection.setConnectTimeout(30000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String fileSize = getFileSize(connection.getContentLengthLong());
//                String fileName = connection.getHeaderField(fileNameField);
                //对url路径做截取
                String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
                InputStream inputStream = connection.getInputStream();
                zipFileExt.setFileSize(fileSize);
                zipFileExt.setFileName(fileName);
                zipFileExt.setInputStream(inputStream);
            }
        } catch (IOException e) {
            log.error("获取网络图片出现异常，图片路径为：{}.异常信息为：{}", url, e.getMessage());
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return zipFileExt;
    }

    public static String getFileUrlSize(String url){
        String result = "0";
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                result = getFileSize(connection.getContentLengthLong());
            }
        } catch (IOException e) {
            log.error("获取网络图片出现异常，图片路径为：{}.异常信息为：{}", url, e.getMessage());
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return result;
    }

    public static String getFileNameByURL(String url){
        String result = "";
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                result = connection.getHeaderField(fileNameField);
            }
        } catch (IOException e) {
            log.error("获取网络图片出现异常，图片路径为：{}.异常信息为：{}", url, e.getMessage());
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 字节转kb/mb/gb
     * @param size
     * @return
     */
    public static String getFileSize(long size) {
        //以B为单位
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //以KB为单位
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //以MB为单位
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //以GB为单位的，先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }
}
